<template>
  <el-dialog
    class="public-dialog"
    title="批量设置不可发区域"
    width="560px"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
    destroy-on-close
  >
    <div>
      <el-form-item label="不可发区域" class="mt-4">
        <el-select
          v-model="form.zip_code_ids"
          placeholder="请选择"
          class="w-[100%]"
          multiple
          collapse-tags
          collapse-tags-tooltip
          clearable
          filterable
        >
          <el-option
            :label="item.region_name"
            :value="item.id"
            v-for="item in options.zipCodeList"
            :key="item"
          />
        </el-select>
      </el-form-item>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { batchAssignZipCodeRegion, getZipCodeRegion } from "../../api/index.js";
import { onMounted, watch } from "vue";
const props = defineProps({
  ids: { type: Array, default: () => [] },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
});
const form = ref({});
const loading = ref(false);
const emit = defineEmits(["update:modelValue", "refresh", "close"]);
onMounted(async () => {
  getList();
});
const options = reactive({
  zipCodeList: [],
});
const getList = async () => {
  const res = await getZipCodeRegion({ match_type: 3 });
  options.zipCodeList = res?.data || [];
};
const handleSave = async () => {
  if (!form.value.zip_code_ids) {
    ElMessage.warning("请选择不可发区域");
    return;
  }
  loading.value = true;
  try {
    const { code, message, data } = await batchAssignZipCodeRegion({
      zip_code_ids: form.value.zip_code_ids,
      id: props.ids,
    });
    if (code !== 200) {
      return;
    }
    if (data.success_data.length) {
      ElMessage.success({
        showClose: true,
        dangerouslyUseHTMLString: true,
        message: data.success_data.join("<br/>"),
      });
    }
    if (data.fail_data.length) {
      ElMessage.error({
        showClose: true,
        duration: 0,
        dangerouslyUseHTMLString: true,
        message: data.fail_data.join("<br/>"),
      });
    }
    handleClose(true);
  } finally {
    loading.value = false;
  }
};
const handleClose = async (refresh) => {
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
<style lang="scss" scoped></style>
